<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-替岗`"
			width="900px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="saveBtnLoading"
			:show-confirm-btn="pageType !== 'detail'"
			:show-cancel-btn="pageType !== 'detail'"
			:show-close-btn="pageType === 'detail'"
			@on-close="onVisibleChange(false)"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="100px" :show-message="false">
				<div ref="box1">
					<div class="flex-between-center margin-bottom-4">
						<el-tag type="primary" effect="plain">
							<span class="el-icon-tickets item-gap"></span>
							<span>基本信息</span>
						</el-tag>
						<div class="flex-end-center">
						</div>
					</div>
					<jk-card class="margin-bottom-10">
						<el-row>
							<el-col :span="12">
								<el-form-item class="margin-bottom-10" label="责任类别" prop="dutyState">
									<span v-if="pageType !== 'add'" class="read-only-2">{{ ruleForm.dutyState === 0 ? '保养' : '巡检' }}</span>
									<jk-select
										v-else
										v-model="ruleForm.dutyState"
										:clearable="true"
										style="width: 100%;"
										:option-list="dutyStateList"
										placeholder="责任类别"
										size="medium"
										@change="onDutyStateChange"
									></jk-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item class="margin-bottom-10" label="被替人员" prop="originalEmpName">
									<span v-if="pageType !== 'add'" class="read-only-2">{{ ruleForm.originalEmpName }}</span>
									<remoteSearchProductInput
										v-else
										placeholder="被替人员"
										only-key="originalEmpCode"
										query-name="originalEmpName"
										size="medium"
										:form-data="ruleForm"
										@on-select="onSelectActualEmpNameChange"
									></remoteSearchProductInput>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item class="margin-bottom-10" label="替工开始" prop="alternateBeginTime">
									<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.alternateBeginTime }}</span>
									<jk-date-picker
										v-else
										v-model="ruleForm.alternateBeginTime"
										:disabled="pageType !== 'add'"
										type="datetime"
										size="medium"
									>
									</jk-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item class="margin-bottom-10" label="替工结束" prop="alternateEndTime">
									<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.alternateEndTime }}</span>
									<jk-date-picker
										v-else
										v-model="ruleForm.alternateEndTime"
										type="datetime"
										size="medium"
									>
									</jk-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
					</jk-card>
				</div>
				<div ref="box2" style="display: flex" class="margin-bottom-4">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-document item-gap"></span>
						<span>替岗明细</span>
					</el-tag>
				</div>
				<jk-table border :data="ruleForm.alternateItemList" :loading="tableLoading" :height="dialogTableHeight - 50">
					<vxe-column title="设备名称" align="left" field="machineName" :width="110" />
					<vxe-column title="设备编码" align="left" field="machineCode" :width="110" />
					<vxe-column title="替岗人" align="left" field="alternateEmpName" :min-width="100">
						<template slot-scope="scope">
							<remoteSearchEmpInput
								size="mini"
								:disabled="pageType === 'detail'"
								placeholder="替岗人"
								only-key="alternateEmpCode"
								query-name="alternateEmpName"
								:form-data="scope.row"
								@on-select="onSelectAlternateEmpNameChange($event, scope.row, scope.rowIndex)"
							></remoteSearchEmpInput>
						</template>
					</vxe-column>
				</jk-table>
			</el-form>
		</jk-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import remoteSearchProductInput from './components/remote-search-product-input/index.vue';
    import remoteSearchEmpInput from '/src/views/production/order/components/remote-search-emp-input';
    import { machineManagerUpkeepPersonnelPage } from '../../../api/machine/upkeepEmp';
    import {
        machinemanagerAlternateCreate,
        machinemanagerAlternateGet,
        machinemanagerAlternateUpdate,
        machinemanagerAlternateHasProcessAuth
    } from '../../../api/machine/replaceJob';

    export default {
        mixins: [calHeight],
        components: { remoteSearchProductInput, remoteSearchEmpInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                processList: [],
                tableLoading: false,
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                showRepairRecord: false,
                ruleForm: {
                    'alternateBeginTime': '',
                    'alternateEndTime': '',
                    'alternateItemList': [],
                    'auditState': 0,
                    'dutyState': 0,
                    'originalEmpCode': '',
                    'originalEmpId': 0,
                    'originalEmpName': '',
                    'personnelId': 0
                },
                rules: {
                    dutyState: [{ required: true, trigger: 'change' }],
                    originalEmpName: [{ required: true, trigger: 'change' }],
                    alternateBeginTime: [{ required: true, trigger: 'change' }],
                    alternateEndTime: [{ required: true, trigger: 'change' }]
                },
                dutyStateList: [
                    { id: 0, name: '保养', code: 'BY' },
                    { id: 1, name: '巡检', code: 'XJ' }
                ],
                machineList: {}
            };
        },
        methods: {
            onSelectAlternateEmpNameChange(e, item, index) {
                this.getProcessAuth(e, item, index);
            },
            getProcessAuth(e, item, index) {
                machinemanagerAlternateHasProcessAuth({ alternateEmpId: e.id, machineId: item.machineId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm.alternateItemList[index].alternateEmpId = e.id;
                        this.ruleForm.alternateItemList[index].alternateEmpCode = e.code;
                        this.ruleForm.alternateItemList[index].alternateEmpName = e.name;
                    }
                });
            },
            onDutyStateChange() {
                this.ruleForm.originalEmpId = null;
                this.ruleForm.originalEmpCode = '';
                this.ruleForm.originalEmpName = '';
                this.ruleForm.alternateItemList = [];
            },
            onSelectActualEmpNameChange(e) {
                this.ruleForm.originalEmpId = e.empId;
                this.ruleForm.originalEmpCode = e.empCode;
                this.ruleForm.originalEmpName = e.empName;

                if (this.ruleForm.dutyState === 1) {
                    this.getPersonnelRequest(e.empId);
                }
            },
            getPersonnelRequest(id) {
                this.tableLoading = true;
                this.ruleForm.alternateItemList = [];
                machineManagerUpkeepPersonnelPage({ empId: id, dutyState: this.ruleForm.dutyState, isAlternate: false }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.getMachinesList(resData);
                    }
                });
            },
            getMachinesList(resData) {
                const resDataList = [];
                resData.forEach(itemMachine => {
                    resDataList.push(...itemMachine.machineList);
                });
                resDataList.forEach(resItem => {
                    this.ruleForm.alternateItemList.push(
                        {
                            'alternateEmpCode': '',
                            'alternateEmpId': 0,
                            'alternateEmpName': '',
                            'alternateId': 0,
                            'createTime': '',
                            'id': null,
                            'machineCode': resItem.machineCode,
                            'machineId': resItem.machineId,
                            'machineName': resItem.machineName,
                            'personnelId': 0,
                            'personnelMachineId': resItem.id
                        }
                    );
                });
                this.tableLoading = false;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    const alternateEmpName = this.ruleForm.alternateItemList.every(obj => obj.alternateEmpName !== null && obj.alternateEmpName !== undefined && obj.alternateEmpName !== '');
                    if (valid && alternateEmpName) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? machinemanagerAlternateCreate : machinemanagerAlternateUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machinemanagerAlternateGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.configItem = resData.configItem || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList || [];
                if (!this.ruleForm.actualEmpName) {
                    this.$set(this.ruleForm, 'actualEmpName', this.ruleForm.planEmpName);
                    this.$set(this.ruleForm, 'actualEmpCode', this.ruleForm.planEmpCode);
                    this.$set(this.ruleForm, 'actualEmpId', this.ruleForm.planEmpId);
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                    this.getDependentData();
                }
            }
        }
    };
</script>
